<template>
  <div v-loading="loading">
    <table class="table table-sm table-bordered approve-table">
      <colgroup>
        <col width="20%" />
        <col width="30%" />
        <col width="20%" />
        <col width="30%" />
      </colgroup>
      <tbody>
        <tr class="bg-light">
          <td colspan="4" class="text-center py-2">{{ label }}</td>
        </tr>
        <template v-if="isView">
          <tr>
            <td>审批金额</td>
            <td>{{ relatedForm.res_funds }}万元</td>
            <td>审批期限</td>
            <td>{{ relatedForm.res_months }}月</td>
          </tr>
          <tr>
            <td>资金实际用途</td>
            <td colspan="3" class="text-left mx-2">{{ relatedForm.funds_use_dir }}</td>
          </tr>
          <tr>
            <td>拟定贷款银行</td>
            <td>{{ relatedForm.bank_name }}</td>
            <td>贷款利率（年）</td>
            <td>{{ relatedForm.load_rate }}%</td>
          </tr>
          <tr>
            <td>担保费收取方式</td>
            <td>
              {{ enumGuaFundsSelfType[relatedForm.gua_fee_coll_type] || '' }}
            </td>
            <td>担保费率</td>
            <td>{{ relatedForm.gua_rate }}%</td>
          </tr>
          <tr>
            <td>项目基本介绍</td>
            <td colspan="3">{{ relatedForm.project_des }}</td>
          </tr>
          <tr>
            <td>反担保措施</td>
            <td colspan="3">{{ relatedForm.gua_method_des }}</td>
          </tr>
          <tr>
            <td>评审会纪要</td>
            <td colspan="3">
              <div v-for="file in areadyFiles" :key="file.url" class="file-item">
                <attach-item :attach-data="file"></attach-item>
              </div>
            </td>
          </tr>
        </template>

        <template v-else>
          <tr>
            <td>审批金额</td>
            <td class="report-input-td">
              <el-input
                v-input-number="{ min: 0, fixed: 4 }"
                placeholder="审批金额"
                v-model="relatedForm.res_funds"
              >
                <span slot="append">万元</span>
              </el-input>
            </td>
            <td>审批期限</td>
            <td class="report-input-td">
              <el-input
                v-input-number="{ min: 0, fixed: 0 }"
                placeholder="审批期限"
                v-model="relatedForm.res_months"
              >
                <span slot="append">月</span>
              </el-input>
            </td>
          </tr>
          <tr>
            <td>资金实际用途</td>
            <td colspan="3" class="report-input-td">
              <textarea
                rows="3"
                class="form-control"
                v-model="relatedForm.funds_use_dir"
              ></textarea>
            </td>
          </tr>
          <tr>
            <td>拟定贷款银行</td>
            <td>
              {{ relatedForm.bank_name }}
            </td>
            <td>贷款利率（年）</td>
            <td class="report-input-td">
              <el-input
                v-input-number="{ min: 0, max: 100, fixed: 2 }"
                placeholder="贷款利率"
                v-model="relatedForm.load_rate"
              >
                <span slot="append">%</span>
              </el-input>
            </td>
          </tr>
          <tr>
            <td>担保费收取方式</td>
            <td class="report-input-td text-left">
              <div style="padding: 0.6rem; background-color: #ffffee">
                <c-radio-group
                  v-model="relatedForm.gua_fee_coll_type"
                  :options="enumGuaFundsSelfType"
                ></c-radio-group>
              </div>
            </td>
            <td>担保费率</td>
            <td class="report-input-td">
              <el-input
                v-input-number="{ min: 0, max: 100, fixed: 2 }"
                placeholder="担保费率"
                v-model="relatedForm.gua_rate"
              >
                <span slot="append">%</span>
              </el-input>
            </td>
          </tr>
          <tr>
            <td>项目基本介绍</td>
            <td colspan="3" class="report-input-td">
              <textarea rows="3" class="form-control" v-model="relatedForm.project_des"></textarea>
            </td>
          </tr>
          <tr>
            <td>反担保措施</td>
            <td colspan="3" class="report-input-td">
              <textarea
                rows="3"
                class="form-control"
                v-model="relatedForm.gua_method_des"
              ></textarea>
            </td>
          </tr>
          <tr>
            <td>评审会纪要</td>
            <td colspan="3" class="report-input-td text-left">
              <div class="d-flex align-items-stretch p-2">
                <div class="mr-3">
                  <input
                    type="file"
                    ref="uploadInput"
                    class="d-none"
                    multiple
                    accept="*"
                    @change="handleFileChange"
                  />
                  <el-button
                    plain
                    size="small"
                    class="mb-1"
                    icon="el-icon-upload2"
                    style="height: 100%"
                    :disabled="saveLoading"
                    @click="handleSelectFile"
                  >
                    上传
                  </el-button>
                </div>
                <div class="flex-1 bg-light p-2 rounded">
                  <div v-for="(file, i) in areadyFiles" :key="file.url" class="file-item">
                    <attach-item :attach-data="file"></attach-item>
                    <el-button type="text" :disabled="saveLoading" @click="handleDeleteFile(1, i)">
                      删除
                    </el-button>
                  </div>
                  <div v-for="(file, index) in uploadFiles" :key="index" class="file-item">
                    <attach-item :attach-data="file"></attach-item>
                    <el-button
                      type="text"
                      :disabled="saveLoading"
                      @click="handleDeleteFile(2, index)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
            </td>
          </tr>
        </template>
      </tbody>
    </table>
    <div class="text-center my-3" v-if="!isView">
      <el-button class="btn-long" type="primary" :loading="saveLoading" @click="handlePass">
        登记
      </el-button>
      <el-button class="btn-long" type="danger" :loading="saveLoading" @click="handleReject">
        拒绝
      </el-button>
      <el-button class="btn-long" :disabled="saveLoading" @click="handleDismiss">取消</el-button>
    </div>
  </div>
</template>

<script>
import { arrayFromString, arrayToString } from '@vimi/utils-tool'
import { uploadOss } from '@/common/api/oss'
import { revokeObjectURL } from '@/common/plugins/tools/file'
import { fileAdapter, attachAdapter } from '@/bank/components/attach/index'
import { exportUrl } from '@/common/api/download'
import { addApprove, updateApprove } from '@/credit/mixin/wf'

import AttachItem from '@/bank/components/attach/Item'
import { enumGuaFundsSelfType } from '@/credit/views/county/unionProvince/components/projectApprove/index'

export default {
  components: {
    AttachItem,
  },
  props: {
    relatedData: {
      type: Object,
      default: () => ({}),
    },
    approveData: {
      type: Object,
      default: () => ({
        editable: false,
        record: [],
      }),
    },
    viewMode: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      enumGuaFundsSelfType,
      loading: false,
      saveLoading: false,
      tableName: 'project_approval_register',

      solidData: {},
      relatedForm: {
        res_funds: '',
        res_months: '',
        funds_use_dir: '',
        bank_name: '',
        load_rate: '',
        gua_rate: '',
        approval_fee: '',
        bond: '',
        project_des: '',
        gua_method_des: '',
        attachment: '',
        gua_fee_coll_type: '',
      },

      areadyFiles: [],
      uploadFiles: [],
    }
  },
  computed: {
    isOnline() {
      return +this.relatedData.review_method === 1
    },
    dataId() {
      return this.solidData.id
    },
    isView() {
      return this.viewMode || !this.approveData.editable
    },
    relatedId() {
      return this.relatedData.customer_related_id
    },
    registerType() {
      return this.approveData.data?.type ?? 2
    },
    label() {
      return this.registerType === 2 ? '评审登记' : '项目审批信息'
    },
  },
  watch: {
    relatedId: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    getData() {
      if (!this.relatedId) return

      this.loading = true

      Promise.all([
        this.$api.getData({
          table: this.tableName,
          params: {
            'customer_related_id.eq': this.relatedId,
            // 'approval_register_type.eq': this.registerType,
          },
        }),
      ])
        .then(([res]) => {
          const data = res?.data ?? []
          const resData = data.find(item => +item.approval_register_type === 1) || {}
          this.solidData = data.find(item => +item.approval_register_type === 2) || {}
          this.initForm(this.dataId ? this.solidData : resData)
        })
        .finally(() => {
          this.loading = false
        })
    },

    initForm(val) {
      this.reset()

      Object.keys(this.relatedForm).forEach(key => {
        this.relatedForm[key] = val[key] || ''
      })

      if (!val.id) {
        const keyMap = {
          funds_use_dir: 'actual_funds_use_dir',
          gua_method_des: 'counter_guarantee',
          res_funds: 'approved_funds',
          res_months: 'months',
          project_des: '',
          bank_name: '',
          load_rate: '',
          gua_rate: '',
          approval_fee: '',
          bond: '',
        }
        Object.keys(keyMap).forEach(key => {
          this.relatedForm[key] = this.relatedData[keyMap[key] || key] || ''
        })
        this.relatedForm.gua_fee_coll_type = this.relatedData.gua_fee_coll_type || '1'
      }

      this.areadyFiles = arrayFromString(val.attachment).reduce((prev, curr) => {
        prev.push(
          attachAdapter({
            attachment: curr,
          })
        )
        return prev
      }, [])
    },

    reset() {
      this.uploadFiles.forEach(file => {
        revokeObjectURL(file.url)
      })
      this.uploadFiles = []
      this.areadyFiles = []
      this.deleteFiles = []

      this.resetInput()
    },

    resetInput() {
      const { uploadInput } = this.$refs
      if (uploadInput) {
        uploadInput.value = ''
      }
    },

    handleFileChange(e) {
      const { files = [] } = e.target

      for (let i = 0; i < files.length; i++) {
        this.uploadFiles.push(fileAdapter(files[i]))
      }

      this.resetInput()
    },

    handleSelectFile() {
      const { uploadInput } = this.$refs
      uploadInput.click()
    },

    handleDeleteFile(type, index) {
      if (type === 2) {
        const file = this.uploadFiles[index]
        revokeObjectURL(file.url)
        this.uploadFiles.splice(index, 1)
      } else {
        this.areadyFiles.splice(index, 1)
      }
    },

    validate() {
      const validatePairs = {
        res_funds: '请填写审批金额',
        res_months: '请填写审批期限',
        bank_name: '请填写拟定贷款银行',
        load_rate: '请填写贷款利率',
        gua_rate: '请填写担保费率',
        // approval_fee: '请填写评审费',
        // bond: '请填写保证金',
        funds_use_dir: '请填写资金实际用途',
        project_des: '请填写项目基本介绍',
        gua_method_des: '请填写反担保措施',
      }

      for (const key in validatePairs) {
        if (!this.relatedForm[key]) {
          return validatePairs[key]
        }
      }
      //  && !this.isOnline
      // if (this.areadyFiles.length + this.uploadFiles.length === 0) {
      //   return '请先上传评审会纪要'
      // }

      return ''
    },

    handlePass() {
      const msg = this.validate()
      if (msg) {
        return this.$message.error(msg)
      }
      this.handleUpdate(1)
    },

    handleReject() {
      const msg = this.validate()
      if (msg) {
        return this.$message.error(msg)
      }
      this.$utils.msgbox({
        message: `确定拒绝项目：${this.relatedData.customer_name}?`,
        type: 'warning',
        beforeClose: () => this.handleUpdate(2),
      })
    },

    handleDismiss() {
      this.$emit('dismiss')
    },

    async handleUpdate(status = 1) {
      const promises = this.uploadFiles.map(it =>
        uploadOss({
          file: it.file,
          dir: `credit/approve/register/${this.relatedId}`,
          type: 0,
          progress: ({ percent }) => {
            it.percent = percent
            it.loading = percent < 100
          },
        })
      )
      this.saveLoading = true
      return Promise.all(promises)
        .then(list => {
          const attachment = arrayToString([...this.areadyFiles.map(it => it.url), ...list])

          // 传空字符串api报错
          const { bond, approval_fee: fee, ...rest } = this.relatedForm
          if (bond) rest.bond = bond
          if (fee) rest.approval_fee = fee

          const data = {
            ...rest,
            customer_related_id: this.relatedId,
            approval_register_type: this.registerType,
            attachment,
          }
          return Promise.all([
            this.dataId ? this.updateData(this.dataId, data) : this.addData(data),
            this.addApproveData(status),
          ])
        })
        .then(res => {
          this.$message.success('登记成功！')
          this.$emit('success', res)
          this.getData()
        })
        .catch(() => {
          this.$message.error('登记失败，请重试！')
        })
        .finally(() => {
          this.saveLoading = false
        })
    },

    addData(data) {
      return this.$api.addData({
        table: this.tableName,
        data,
      })
    },

    updateData(id, data) {
      return this.$api.updateData({
        table: this.tableName,
        id,
        data,
      })
    },

    addApproveData(status) {
      const { id, task_id: taskId } = this.approveData.record.find(it => it.editable) || {}
      if (!taskId) return Promise.resolve()
      const { process } = this.approveData

      const data = {
        opinion: '',
        status,
        process,
        taskId,
      }

      return id
        ? updateApprove(id, data, this.$store.getters.user)
        : addApprove(this.relatedId, data, this.$store.getters.user)
    },

    handleDownloadFile(attach) {
      const { attachment: url, name } = attach
      exportUrl({
        url,
        filename: name,
      })
    },
  },
}
</script>

<style lang="scss" scoped>
@import './index.scss';

.file-item {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px dotted #eee;

  &:last-child {
    border-bottom: none;
  }
}
</style>
